import React, { useMemo, useEffect, useState } from "react";
import { Button, Checkbox, Space, DatePicker, message, Popconfirm, Image, Select as AntdSelect, Tooltip } from "antd";
import { PrefixPlaceholder, Input, Select, BatchSuffixInput } from "@/views/components/PrefixPlaceholder";
import BtnGroup from "@/views/components/BtnGroup";
import RangeDisablePicker from "@/views/components/RangeDisablePicker";
import moment from "moment";
import { isEmpty, find, filter } from "lodash";
import { queryTakeUserList, auditingMemberPriceApply } from "./service";
import { customTrimFunc } from "@/utils/utils.jsx";
import ApplyMemberPrice from "./components/Actions/ApplyMemberPrice";
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD HH:mm:ss";

const NewAntdSelect = ({ ...args }) => {
	useEffect(() => {
		if (args?.onChange) {
			args?.onChange(args?.defaultValue);
		}
	}, []);
	return <AntdSelect {...args} />;
};

const status1Cols = [
	"序号",
	"图片",
	"系统商品名称",
	"系统款式编码",
	"系统商品编码",
	"系统颜色",
	"系统尺寸",
	"匹配类型",
	"供应商名称",
	"档口号",
	"供应商商品名称",
	"供应商颜色规格",
	"供应商款式编码",
	"供应商商品编码",
	"供应商商品图片",
	"商城价（元）",
	"申请/修改会员价（元）",
	"申请时间",
	"审核时间"
];

const status2Cols = [
	"序号",
	"图片",
	"系统商品名称",
	"系统款式编码",
	"系统商品编码",
	"系统颜色",
	"系统尺寸",
	"匹配类型",
	"供应商名称",
	"档口号",
	"供应商商品名称",
	"供应商颜色规格",
	"供应商款式编码",
	"供应商商品编码",
	"供应商商品图片",
	"采购价（元）",
	"会员价（元）",
	// "申请/修改会员价（元）",
	// "申请时间",
	"审核时间",
	"审核失败原因"
];

const status3Cols = [
	"序号",
	"图片",
	"系统商品名称",
	"系统款式编码",
	"系统商品编码",
	"系统颜色",
	"系统尺寸",
	"匹配类型",
	"供应商名称",
	"档口号",
	"供应商商品名称",
	"供应商颜色规格",
	"供应商款式编码",
	"供应商商品编码",
	"供应商商品图片",
	"审核时间",
	"作废时间"
];

const ImageBox = ({ children }) => {
	return <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>{children}</div>;
};

const formatZjfImg = ({ img, storeId, size = 48 }) => {
	//检测图片是否是完整路径，如果不是需要拼接
	if (!img) {
		return `https://imgniu.zhaojiafang.com/no-img${48}.jpg`;
	}
	if (/^(http|https)/.test(img)) {
		if (/zhaojiafang/.test(img)) {
			return size ? `${img}_${size}x${size}` : img;
		} else {
			return img;
		}
	} else {
		return size
			? `https://imgniu.zhaojiafang.com/store/goods/${storeId}/${img}_${size}x${size}`
			: `https://imgniu.zhaojiafang.com/store/goods/${storeId}/${img}`;
	}
};

export const getColumns = ({ cbRef, status = 0 }) => {
	const [userData, setUserData] = useState([]); // 拿货员列表

	const handleUserList = async username => {
		const { data, success } = await queryTakeUserList(customTrimFunc({ username, current: 1, size: 20, businessType: 3 }));
		if (success) {
			setUserData(data);
		}
	};

	useEffect(() => {
		handleUserList();
	}, []);

	//渲染交接员工
	const renderSubUser = item => {
		if (item.name) {
			if (item.account) {
				return item.name + "(" + item.account + ")";
			} else {
				return item.name;
			}
		} else {
			return "";
		}
	};

	const optionUserList =
		!isEmpty(userData) &&
		userData.map(item => (
			<Option key={item.id} value={item.id}>
				<Tooltip title={renderSubUser(item)}>{renderSubUser(item)}</Tooltip>
			</Option>
		));

	const columnsMemo = useMemo(() => {
		let columns = [
			{
				hidden: true,
				search: {
					order: 1,
					code: "isMatchAuditing",
					content: () => (
						<Select
							placeholder="是否由供应商审核"
							options={[
								{ label: "是", value: 1 },
								{ label: "否", value: 0 }
							]}
						/>
					)
				}
			},
			{
				name: "序号",
				code: "index",
				align: "center",
				render: (t, r, i) => i + 1,
				lock: true,
				width: 55
			},

			{
				name: "图片",
				code: "image",
				width: 55,
				render: (src, record, i) => (
					<>
						<Image className="auto" src={src} />
					</>
				)
			},
			{
				name: "系统商品名称",
				code: "skuName",
				width: 200,
				search: {
					order: 8,
					content: () => <Input placeholder="系统商品名称" />
				}
			},
			{
				name: "系统款式编码",
				code: "spuCode",
				width: 200,
				search: {
					order: 9,
					content: () => <Input placeholder="系统款式编码" />
				}
			},
			{
				name: "系统商品编码",
				code: "skuCode",
				width: 200,
				search: {
					order: 10,
					content: () => <Input placeholder="系统商品编码" />
				}
			},
			{
				name: "系统颜色",
				code: "colour",
				width: 150
			},
			{
				name: "系统尺寸",
				code: "specs"
			},
			{
				name: "商城价（元）",
				code: "mallPrice"
			},
			{
				name: "原会员价（元）",
				code: "oldPrice"
			},
			{
				name: "申请/修改会员价（元）",
				code: "newPrice"
			},
			{
				name: "匹配类型",
				code: "matchType",
				render(txt) {
					return txt == "1" ? "供应商匹配" : "精准匹配";
				}
			},
			{
				name: "供应商名称",
				code: "supplierName",
				search: {
					order: 2,
					content: () => <Input placeholder="供应商名称" />
				}
			},
			{
				name: "档口号",
				code: "shopCode",
				search: {
					order: 3,
					content: () => <Input placeholder="档口号" />
				}
			},
			{
				name: "供应商商品名称",
				code: "supplierSkuName",
				width: 200,
				search: {
					order: 4,
					content: () => <Input placeholder="供应商商品名称" />
				}
			},
			{
				hidden: true,
				search: {
					order: 11,
					code: "colorSpecifications",
					content: () => <Input placeholder="系统颜色及尺码" />
				}
			},
			{
				hidden: true,
				search: {
					span: 6,
					order: 12,
					group:
						status === 0
							? [
									{
										code: "dateType",
										span: 0,
										content: () => {
											return (
												<NewAntdSelect defaultValue={1} placeholder="申请时间" className="right-no-radius width-full">
													<Option value={1}>申请时间</Option>
												</NewAntdSelect>
											);
										}
									},
									{
										keys: ["startTime", "endTime"],
										code: "time",
										span: 24,
										content: () => (
											<RangePicker
												format={dateFormat}
												placeholder={status === 0 ? ["申请开始日期", "结束日期"] : ["开始日期", "结束日期"]}
												showTime
												className="left-no-radius"
												style={{ width: "100%" }}
											/>
										)
									}
								]
							: [
									{
										code: "dateType",
										span: 6,
										content: () => {
											return status == 0 ? (
												<Input
													origin="true"
													style={{
														borderLeft: 0,
														borderRight: 0,
														pointerEvents: "none"
													}}
													placeholder="申请时间"
													disabled
												/>
											) : (
												<NewAntdSelect
													defaultValue={status == 3 ? 3 : 1}
													placeholder={status == 3 ? "作废时间" : "申请时间"}
													className="right-no-radius width-full"
												>
													{status == 3 && (
														<>
															<Option value={3}>作废时间</Option>
														</>
													)}
													<Option value={1}>申请时间</Option>
													{status != 0 && (
														<>
															<Option value={2}>审核时间</Option>
														</>
													)}
												</NewAntdSelect>
											);
										}
									},
									{
										keys: ["startTime", "endTime"],
										code: "time",

										span: 18,
										content: () => <RangePicker format={dateFormat} showTime className="left-no-radius" />
									}
								]
				}
			},
			{
				name: "供应商颜色规格",
				code: "supplierSkuSpecs",
				width: 200,
				search: {
					order: 7,
					code: "supplierSkuSpecs",
					content: () => <Input placeholder="供应商颜色尺寸" />
				}
			},
			{
				name: "供应商款式编码",
				code: "supplierSpuCode",
				width: 200,
				search: {
					order: 5,
					content: () => <Input placeholder="供应商款式编码" />
				}
			},
			{
				name: "供应商商品编码",
				code: "supplierSkuId",
				width: 200,
				search: {
					order: 6,
					content: () => (
						<Input
							placeholder="供应商商品编码"
							onInput={e => {
								const { keyCode, key, target } = e;
								if (/^[0-9,]*$/g.test(target.value)) {
									return;
								}
								target.value = target.value.replace(/[^\d]/g, "");
							}}
						/>
					)
				}
			},
			{
				name: "供应商商品图片",
				code: "supplierSkuImage",
				width: 130,
				render: (_, record) => {
					console.log(
						"%celelee test:",
						"background:#000;color:#fff",
						formatZjfImg({ img: record.supplierSkuImage, storeId: record.supplierId, size: 0 })
					);
					return (
						<ImageBox>
							<Image
								height={32}
								width={32}
								src={formatZjfImg({ img: record.supplierSkuImage, storeId: record.supplierId, size: 0 })}
							></Image>
						</ImageBox>
					);
				}
			},
			{
				name: "拿货员",
				code: "pickerUser",
				render: (_, record) => {
					return record.pickerName ? record.pickerName : "";
				},
				search: {
					order: 13,
					content: () => <Select placeholder="拿货员">{optionUserList}</Select>
				}
			},
			{
				name: "发起人",
				code: "applyName",
				search: {
					order: 14,
					content: () => <Input placeholder="发起人" />
				}
			},
			{
				hidden: true,
				search: {
					order: 15,
					code: "matchType",
					content: () => (
						<Select
							placeholder="匹配类型"
							options={[
								{ label: "供应商匹配", value: "1" },
								{ label: "精准匹配", value: "2" }
							]}
						/>
					)
				}
			},
			{
				name: "申请时间",
				code: "applyTime",
				render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
				width: 200
			}
		];

		if (status != 0) {
			let tmp = [];
			switch (status) {
				case 1:
					tmp = status1Cols;
					break;
				case 2:
					tmp = status2Cols;
					break;
				case 3:
					tmp = status3Cols;
					break;
				default:
					break;
			}

			columns = columns.filter(item => (!item.name ? true : tmp.includes(item.name)));
			if (status == 1 || status == 3) {
				// 删除columns中 search的code是isMatchAuditing的元素
				columns = columns.filter(item => item.search?.code !== "isMatchAuditing");
				columns.forEach(item => {
					if (item.name === "申请/修改会员价（元）") {
						item.name = "会员价（元）";
					}
				});
			}
			if (status == 2) {
				columns.push(
					{
						name: "采购价（元）",
						code: "mallPrice"
					},
					{
						name: "原会员价（元）",
						code: "oldPrice",
						width: 150
					},
					{
						name: "申请/修改会员价（元）",
						code: "newPrice",
						width: 180
					}
				);
				columns.push(
					{
						name: "申请时间",
						code: "applyTime",
						render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
						width: 200
					},
					{
						name: "审核时间",
						code: "auditingTime",
						render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
						width: 200
					}
				);
				columns.push({
					name: "审核失败原因",
					code: "reason"
				});
			}

			if (status == 3) {
				// 给columns这个数组 倒数第二个列后面加入 “作废时间”
				columns.push(
					{
						name: "商城价（元）",
						code: "mallPrice"
					},
					{
						name: "会员价（元）",
						code: "newPrice"
					},
					{
						name: "申请时间",
						code: "applyTime",
						render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
						width: 200
					},
					{
						name: "审核时间",
						code: "auditingTime",
						render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
						width: 200
					},
					{
						name: "作废时间",
						code: "nullifyTime",
						render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
						width: 200
					},
					{
						lock: true,
						code: "action",
						name: "操作",
						align: "center",
						render(_, record) {
							return (
								<>
									<ApplyMemberPrice
										type="link"
										text="重新申请"
										selectedIds={[record.skuId]}
										selectedSkuCodes={[record.skuCode]}
										onSubmitSuccess={cbRef.current}
									/>
									{/* <Popconfirm
										placement="leftTop"
										title="确定重新申请吗？"
										onConfirm={() => {
											// auditingMemberPriceApply({ id: record.id, status: 1 }).then(() => {
											// 	cbRef.current();
											// 	message.success("操作成功");
											// });
										}}
										onCancel={() => {}}
									>
										<Button type="link">重新申请</Button>
									</Popconfirm> */}
								</>
							);
						}
					}
				);
			}
		}

		if (status == 0) {
			columns.push({
				lock: true,
				code: "action",
				name: "操作",
				align: "center",
				render(_, record) {
					if (record.isMatchAuditing == 1) {
						return (
							<Button type="link" disabled>
								待供应商审核
							</Button>
						);
					}

					return (
						<>
							<Popconfirm
								placement="leftTop"
								title="确定审核通过吗？"
								onConfirm={() => {
									auditingMemberPriceApply({ id: record.id, status: 1 }).then(() => {
										cbRef.current();
										message.success("操作成功");
									});
								}}
								onCancel={() => {}}
							>
								<Button type="link">同意</Button>
							</Popconfirm>
							<Popconfirm
								placement="leftTop"
								title="确定拒绝申请吗？"
								onConfirm={() => {
									auditingMemberPriceApply({ id: record.id, status: 2 }).then(() => {
										cbRef.current();
										message.success("操作成功");
									});
								}}
								onCancel={() => {}}
							>
								<Button type="link">拒绝</Button>
							</Popconfirm>
						</>
					);
				}
			});
		}

		if (status == 1) {
			columns.push({
				name: "审核时间",
				code: "auditingTime",
				render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
				width: 200
			});
		}

		return columns;
	}, [userData]);

	return { columns: columnsMemo };
};

export const getLogColumns = props => {
	const [userData, setUserData] = useState([]); // 拿货员列表

	const handleUserList = async username => {
		const { data, success } = await queryTakeUserList(customTrimFunc({ username, current: 1, size: 20, businessType: 3 }));
		if (success) {
			setUserData(data);
		}
	};

	useEffect(() => {
		handleUserList();
	}, []);

	//渲染交接员工
	const renderSubUser = item => {
		if (item.name) {
			if (item.account) {
				return item.name + "(" + item.account + ")";
			} else {
				return item.name;
			}
		} else {
			return "";
		}
	};

	const optionUserList =
		!isEmpty(userData) &&
		userData.map(item => (
			<Option key={item.id} value={item.id}>
				<Tooltip title={renderSubUser(item)}>{renderSubUser(item)}</Tooltip>
			</Option>
		));

	const columns = [
		{
			name: "序号",
			code: "index",
			align: "center",
			render: (t, r, i) => i + 1,
			lock: true,
			width: 55
		},

		{
			name: "图片",
			code: "image",
			width: 55,
			render: (src, record, i) => (
				<>
					<Image className="auto" src={src || record.skuImage} />
				</>
			)
		},
		{
			name: "商品名称",
			code: "skuName",
			width: 150,
			search: {
				order: 2,
				content: () => <Input placeholder="商品名称" />
			}
		},
		{
			name: "颜色",
			code: "colour"
		},
		{
			name: "尺寸",
			code: "specs"
		},
		{
			name: "款式编码",
			code: "spuCode",
			width: 150,
			search: {
				order: 4,
				content: () => <Input placeholder="款式编码" />
			}
		},
		{
			name: "商品编码",
			code: "skuCode",
			width: 200,
			search: {
				order: 3,
				content: () => <Input placeholder="商品编码" />
			}
		},
		{
			name: "原会员价（元）",
			code: "oldPrice"
		},
		{
			name: "申请/修改会员价（元）",
			code: "newPrice"
		},
		{
			name: "匹配类型",
			code: "matchType",
			render(txt) {
				return txt == "1" ? "供应商匹配" : "精准匹配";
			}
		},
		{
			name: "供应商名称",
			code: "supplierName",
			search: {
				order: 9,
				content: () => <Input placeholder="供应商名称" />
			}
		},
		{
			hidden: true,
			name: "档口号",
			code: "shopCode",
			search: {
				order: 10,
				code: "shopCode",
				content: () => <Input placeholder="档口号" />
			}
		},
		{
			name: "档口号",
			code: "shopCode",
			width: 200
		},
		{
			name: "供应商商品名称",
			code: "supplierSkuName",
			width: 200,
			search: {
				order: 11,
				content: () => <Input placeholder="供应商商品名称" />
			}
		},
		{
			name: "供应商颜色规格",
			code: "supplierSkuSpecs",
			width: 200
		},
		{
			name: "供应商款式编码",
			code: "supplierSpuCode",
			width: 200,
			search: {
				order: 12,
				content: () => <Input placeholder="供应商款式编码" />
			}
		},
		{
			name: "供应商商品编码",
			code: "supplierSkuId",
			width: 200,
			search: {
				order: 13,
				content: () => (
					<Input
						placeholder="供应商商品编码"
						onInput={e => {
							const { keyCode, key, target } = e;
							if (/^[0-9,]*$/g.test(target.value)) {
								return;
							}
							target.value = target.value.replace(/[^\d]/g, "");
						}}
					/>
				)
			}
		},
		{
			hidden: true,
			search: {
				order: 14,
				code: "supplierSkuSpecs",
				content: () => <Input placeholder="供应商颜色尺寸" />
			}
		},
		{
			hidden: true,
			search: {
				span: 6,
				order: 1,
				keys: ["auditingStartTime", "auditingEndTime"],
				code: "time",
				content: () => <RangePicker format={dateFormat} showTime className="left-no-radius" style={{ width: "100%" }} />
			}
		},
		{
			name: "拿货员",
			code: "pickerUser",
			render: (_, record) => {
				return record.pickerName ? record.pickerName : "";
			},
			search: {
				order: 5,
				content: () => <Select placeholder="拿货员">{optionUserList}</Select>
			}
		},
		{
			name: "发起人",
			code: "applyName",
			search: {
				order: 6,
				content: () => <Input placeholder="发起人" />
			}
		},
		{
			hidden: true,
			search: {
				order: 15,
				code: "matchType",
				content: () => (
					<Select
						placeholder="匹配类型"
						options={[
							{ label: "供应商匹配", value: "1" },
							{ label: "精准匹配", value: "2" }
						]}
					/>
				)
			}
		},
		{
			name: "审核人",
			code: "auditingName",
			search: {
				order: 7,
				content: () => <Input placeholder="审核人"></Input>
			}
		},
		{
			name: "状态",
			code: "status",
			render(txt) {
				const statusMap = {
					0: "待审核",
					1: "使用中",
					2: "审核失败",
					3: "作废"
				};
				return statusMap[txt] || "";
			},
			search: {
				order: 8,
				content: () => (
					<Select
						placeholder="状态"
						options={[
							// { label: "待审核", value: "0" },
							{ label: "使用中", value: "1" },
							{ label: "审核失败", value: "2" }
							// { label: "作废", value: "3" }
						]}
					/>
				)
			}
		},

		{
			name: "审核时间",
			code: "auditingTime",
			render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
			width: 200
		},
		{
			lock: true,
			code: "action",
			name: "操作",
			align: "center",
			render(_, record) {
				return record.status == 2 ? <></> : <>{props.actionBtns(record)}</>;
			}
		}
	];

	return { columns };
};
